import {getUserTempId} from '@/utils/userAbout'
import {reqCode, reqLogin, reqLogout, reqRegister, reqUserAddressList, reqUserInfo} from '@/api'
/*import controller from "swiper/src/components/controller/controller";*/

const state = {
    // 初始化的时候就获取用户的临时标识存储到这里
    userTempId: getUserTempId(),
    code: '',
/*    token: '',//一开始做的时候要是''*/
    token:localStorage.getItem('TOKEN_KEY'),//从localStorage获取值 如果没有 就是null
    userInfo: {},
    userAddressList:[]
}
const mutations = {
    RECEIVE_CODE(state, code) {
        state.code = code
    },
    RECEIVE_USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    RECEIVE_TOKEN(state, token) {
        state.token = token
    },
    RESET_TOKEN(state,token){
        state.token=""
        state.userInfo={}
    },
    RECEIVE_USERADDRESSLIST(state,userAddressList){
        state.userAddressList=userAddressList
    }

}
const actions = {
    //获取验证码
    async getCode({commit}, phone) {
        const result = await reqCode(phone)
        if (result.code === 200) {
            commit('RECEIVE_CODE')
            return result.data
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    //注册
    async getRegister({commit}, userInfo) {
        const result = await reqRegister(userInfo)
        if (result.code === 200) {
            commit('RECEIVE_USERINFO')
            return result.data
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    //登录
    async getLogin({commit}, userInfo) {
        const result = await reqLogin(userInfo)
        if (result.code === 200) {
            commit('RECEIVE_TOKEN', result.data.token)
            //localStorage 存一下token的信息
            localStorage.setItem('TOKEN_KEY',result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    //获取用户信息
    async getUserInfo({commit}, userInfo) {
        const result = await reqUserInfo()
        if (result.code === 200) {
            commit('RECEIVE_USERINFO', result.data)
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    //清空token
    async resetToken({commit}){
        commit('RESET_TOKEN')//清空state内部的token
        localStorage.removeItem('TOKEN_KEY')//清空localStorage内部的token信息
    },
   //退出登录
    async getLogout({commit,dispatch}){
        const result=await reqLogout()
        if (result.code===200){
            dispatch('resetToken')
            //退成登录成功，清空当前state当中的token和用户信息，还有localStorage内部的token信息
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
//获取用户地址
async getUserAddressList({commit}){
        const result=await reqUserAddressList()
    if (result.code===200){
        commit('RECEIVE_USERADDRESSLIST',result.data)
    }
}
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}
